package com.uil.fileutil.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;


/**
 * 读取文件（可读取多个文件夹下的文件）  转成base64编码 输出到有对应结构的目录的文件夹（.txt）
 * @author liu
 */
public class FileToBase64Converter {

    public static void To(String folderPath, String outputFolderPath) {
        // 创建输出文件夹路径
        createFolder(outputFolderPath);

        // 读取文件夹内的文件并进行处理
        processFilesInFolder(folderPath, outputFolderPath);
    }

    private static void processFilesInFolder(String inputFolderPath, String outputFolderPath) {
        File folder = new File(inputFolderPath);
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    String fileName = file.getName();

                    // 将文件转换为Base64编码
                    String base64String = convertFileToBase64(file);

                    // 将Base64编码写入到txt文档中
                    writeBase64ToFile(base64String, outputFolderPath, fileName);
                } else if (file.isDirectory()) {
                    // 递归处理子文件夹
                    String outputSubFolderPath = outputFolderPath + File.separator + file.getName();
                    createFolder(outputSubFolderPath);
                    processFilesInFolder(file.getAbsolutePath(), outputSubFolderPath);
                }
            }
        }
    }

    private static String convertFileToBase64(File file) {
        try {
            byte[] fileContent = Files.readAllBytes(file.toPath());
            return Base64.getEncoder().encodeToString(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void writeBase64ToFile(String base64String, String outputFolderPath, String fileName) {
        try {
            String filePath = outputFolderPath + File.separator + fileName + ".txt";
            BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
            writer.write(base64String);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void createFolder(String folderPath) {
        Path path = Paths.get(folderPath);
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}